package com.shsubway.activity.manger;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.shsubway.R;
import com.shsubway.activity.staff.LookQuestionsActivity;
import com.shsubway.adapter.MakeQAdapter;
import com.shsubway.base.BaseActivity;
import com.shsubway.model.AnswerEntity;
import com.shsubway.model.QuestionEntity;
import com.shsubway.utils.Constant;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 录入题库及修改题库
 */
public class MakeQuestionActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    RadioGroup chooseBtn;
    MaterialEditText editQuery;
    @BindView(R.id.ans_list)
    RecyclerView ansListView;


    Button addAnsBtn;
    Button saveNextBtn;
    Button saveBtn;
    List<AnswerEntity> answerEntities;
    MakeQAdapter makeQAdapter;
    int ALL_ANS = 4;//选项的数量
    private static final String TAG = "MakeQuestionActivity--";
    int CHOOSE_TYPE = 1;//题的难易程度
    int QUES_TYPE = 0;//题型的选择
    Spinner chooseSpinner;
    boolean isnext = false;
    View heardView, footView;
    Intent intent;
    Bundle bundle;
    QuestionEntity questionEntity;
    boolean isUpdate = false;
    String objectId;
    @BindView(R.id.del_all)
    ImageView delAll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_make_question);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        saveNextBtn.setOnClickListener(this);
        saveBtn.setOnClickListener(this);
        addAnsBtn.setOnClickListener(this);
        chooseSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (!isUpdate) {
                        //分析：当前是单选 如果是从判断跳转进入的 则清空list 恢复条目为4
                        //如果从多选过来那就只
                        if (QUES_TYPE != 1) {
                            answerEntities.clear();
                            ALL_ANS = 4;
                            initData();
                            makeQAdapter.setQesType(position);
                            makeQAdapter.notifyDataSetChanged();

                        } else {
                            makeQAdapter.setQesType(position);
                        }
                        addAnsBtn.setVisibility(View.VISIBLE);
                        QUES_TYPE = position;
                    } else if (QUES_TYPE != position) {
                        if (QUES_TYPE != 1) {
                            answerEntities.clear();
                            ALL_ANS = 4;
                            initData();
                            makeQAdapter.setQesType(position);
                            makeQAdapter.notifyDataSetChanged();

                        } else {
                            makeQAdapter.setQesType(position);
                        }
                        addAnsBtn.setVisibility(View.VISIBLE);
                        QUES_TYPE = position;
                    }
                } else if (position == 1) {
                    if (!isUpdate) {
                        /**
                         * 分析：如果是多选 判断是否是从判断进入的 如果是的话 则清空list 恢复条目为4
                         *  如果是从单选进入那么维持现状
                         */
                        if (QUES_TYPE != 0) {
                            answerEntities.clear();
                            ALL_ANS = 4;
                            initData();
                            makeQAdapter.setQesType(position);
                            makeQAdapter.notifyDataSetChanged();

                        } else {
                            makeQAdapter.setQesType(position);

                        }
                        addAnsBtn.setVisibility(View.VISIBLE);
                        QUES_TYPE = position;
                    } else {
                        //如果是修改的状态
                        if (QUES_TYPE != position) {

                            if (QUES_TYPE != 0) {
                                answerEntities.clear();
                                ALL_ANS = 4;
                                initData();
                                makeQAdapter.setQesType(position);
                                makeQAdapter.notifyDataSetChanged();

                            } else {
                                makeQAdapter.setQesType(position);

                            }
                            addAnsBtn.setVisibility(View.VISIBLE);
                            QUES_TYPE = position;

                        }


                    }
                } else if (position == 2) {

                    if (!isUpdate) {
                        AlertDialog.Builder normalDialog =
                                new AlertDialog.Builder(context);
                        normalDialog.setIcon(R.mipmap.ic_launcher);
                        normalDialog.setTitle("确定更改为判断题型吗？");
                        normalDialog.setMessage("如更改为判断题选项会自动清空数据无法回撤，慎重。");
                        normalDialog.setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        addAnsBtn.setVisibility(View.GONE);
                                        //...To-do
                                        answerEntities.clear();
                                        ALL_ANS = 2;
                                        initData();
                                        addAnsBtn.setVisibility(View.GONE);
                                        makeQAdapter.setQesType(position);
                                        makeQAdapter.notifyDataSetChanged();
                                        QUES_TYPE = position;
                                    }
                                });
                        normalDialog.setNegativeButton("算了",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //...To-do
                                        dialog.dismiss();
                                        chooseSpinner.setSelection(QUES_TYPE, true);
                                    }
                                });
                        // 显示
                        normalDialog.show();

                    } else {
                        //如果是修改
                        if (QUES_TYPE != position) {
                            AlertDialog.Builder normalDialog =
                                    new AlertDialog.Builder(context);
                            normalDialog.setIcon(R.mipmap.ic_launcher);
                            normalDialog.setTitle("确定更改为判断题型吗？");
                            normalDialog.setMessage("如更改为判断题选项会自动清空数据无法回撤，慎重。");
                            normalDialog.setPositiveButton("确定",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            addAnsBtn.setVisibility(View.GONE);
                                            //...To-do
                                            answerEntities.clear();
                                            ALL_ANS = 2;
                                            initData();
                                            addAnsBtn.setVisibility(View.GONE);
                                            makeQAdapter.setQesType(position);
                                            makeQAdapter.notifyDataSetChanged();
                                            QUES_TYPE = position;
                                        }
                                    });
                            normalDialog.setNegativeButton("算了",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            //...To-do
                                            dialog.dismiss();
                                            chooseSpinner.setSelection(QUES_TYPE);
                                        }
                                    });
                            // 显示
                            normalDialog.show();
                        }


                    }

                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        ansListView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                adapter.remove(position);
                adapter.notifyDataSetChanged();
            }
        });
        chooseBtn.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {
                    case R.id.easy_btn:
                        CHOOSE_TYPE = 0;
                        break;
                    case R.id.com_btn:
                        CHOOSE_TYPE = 1;
                        break;
                    case R.id.hard_btn:
                        CHOOSE_TYPE = 2;
                        break;
                }

            }
        });


    }

    private void initView() {

        intent = getIntent();
        bundle = intent.getExtras();
        answerEntities = new ArrayList<>();
        initHeardView();
        initFootView();
        getIsUpdate();
        initAdapter();
        //如果是修改状态
        if (isUpdate) {
            questionEntity = (QuestionEntity) bundle.getSerializable(Constant.QUESTION);
            QUES_TYPE = questionEntity.getQsttype();
            chooseSpinner.setSelection(QUES_TYPE);
            setTitleBar(toolbar, "编辑");
            answerEntities.addAll(questionEntity.getAnswerEntities());
            makeQAdapter.setQesType(4);
            makeQAdapter.setNewData(answerEntities);
            //设置heardview
            setRadioBtn();
            editQuery.setText(questionEntity.getQstcontent());
            saveNextBtn.setVisibility(View.GONE);
            saveBtn.setText("完成");
            objectId = questionEntity.getObjectId();
        } else {
            setTitleBar(toolbar, "录入");
            initData();
        }
    }

    private void setRadioBtn() {
        switch (questionEntity.getEasyconhardtype()) {
            case 0:
                chooseBtn.check(R.id.easy_btn);
                break;
            case 1:
                chooseBtn.check(R.id.com_btn);
                break;
            case 2:
                chooseBtn.check(R.id.hard_btn);
                break;
        }
    }

    private void getIsUpdate() {
        if (bundle.getString(Constant.TAG).equals(LookQuestionsActivity.class.getSimpleName())) {
            isUpdate = true;
        } else {
            isUpdate = false;
        }
    }

    private void initHeardView() {
        heardView = View.inflate(context, R.layout.heard_view_make_question, null);
        chooseSpinner = $(R.id.choose_spinner, heardView);
        chooseBtn = $(R.id.choose_btn, heardView);
        editQuery = $(R.id.edit_query, heardView);


    }

    private void initFootView() {
        footView = View.inflate(context, R.layout.foot_view_make_question, null);
        saveNextBtn = $(R.id.save_next_btn, footView);
        saveBtn = $(R.id.save_btn, footView);
        addAnsBtn = $(R.id.add_ans_btn, footView);

    }

    private void initData() {
        for (int i = 0; i < ALL_ANS; i++) {
            addAnswer();
        }
    }

    private void addAnswer() {
        AnswerEntity answerEntity = new AnswerEntity();
        answerEntities.add(answerEntity);
    }

    private void initAdapter() {
        setRecy(ansListView);
        makeQAdapter = new MakeQAdapter(R.layout.item_make_question, answerEntities);
        makeQAdapter.setEmptyView(emptyView);
        ansListView.setAdapter(makeQAdapter);
        makeQAdapter.addHeaderView(heardView);
        makeQAdapter.addFooterView(footView);
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_ans_btn:
                addAnswer();
                makeQAdapter.notifyItemInserted(answerEntities.size());
                break;
            case R.id.save_next_btn:
                chooseBtn.getCheckedRadioButtonId();



                isnext = true;
                checknull();
                break;
            case R.id.save_btn:
                isnext = false;
                checknull();
                break;
        }
    }

    private void comit() {
        QuestionEntity qust = new QuestionEntity();
        qust.setQsttype(QUES_TYPE);
        qust.setQstcontent(editQuery.getText().toString().trim());
        qust.setEasyconhardtype(CHOOSE_TYPE);
        qust.setAnswerEntities(answerEntities);


        if (isUpdate) {
            qust.update(objectId, new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        toast("成功");
                        //TODO 设置返回
                    } else {
                        toast("失败");
                    }
                }
            });
        } else {
            qust.save(new SaveListener<String>() {
                @Override
                public void done(String s, BmobException e) {
                    if (e == null) {
                        toast("成功");
                        if (isnext) {
                            answerEntities.clear();
                            editQuery.setText("");
                            initData();
                            makeQAdapter.notifyDataSetChanged();
                            isnext = false;
                        } else {
                            finish();
                        }
                    } else {
                        toast("失败");
                    }
                }
            });
        }


    }


    private void checknull() {
        if (!TextUtils.isEmpty(editQuery.getText())) {
            for (AnswerEntity answerEntity : answerEntities) {
                if (TextUtils.isEmpty(answerEntity.getAnscontent())) {
                    toast("选项若没有内容，请删除此项。");
                    return;
                }
            }
            comit();

        } else {
            toast("题目不能为空");
        }
    }


    @OnClick(R.id.del_all)
    public void onClick() {
        QuestionEntity qust = new QuestionEntity();
        qust.delete(objectId, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    toast("删除成功");
                    //TODO 设置返回
                } else {
                    toast("失败");
                }
            }
        });
    }
}
